<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Electron Hello World</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .container {
            text-align: center;
            padding: 40px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .container::-webkit-scrollbar {
            width: 8px;
        }
        
        .container::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
        }
        
        .container::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 10px;
        }
        
        .container::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }
        
        h1 {
            font-size: 3em;
            margin: 0 0 20px 0;
            animation: fadeInDown 1s ease;
        }
        
        p {
            font-size: 1.2em;
            margin: 10px 0;
            animation: fadeInUp 1s ease;
        }
        
        .info {
            margin-top: 30px;
            font-size: 0.9em;
            opacity: 0.9;
            text-align: left;
            max-width: 600px;
        }
        
        .info h3 {
            font-size: 1.2em;
            margin: 20px 0 10px 0;
            text-align: center;
            color: #fff;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        
        .info p {
            margin: 8px 0;
            padding: 5px 10px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 5px;
            font-size: 0.85em;
        }
        
        .info strong {
            color: #ffd700;
            font-weight: 600;
        }
        
        .info span {
            color: #90EE90;
            font-family: 'Monaco', 'Courier New', monospace;
        }
        
        .file-selector {
            margin-top: 30px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 10px;
        }
        
        .file-selector button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            font-size: 1em;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        
        .file-selector button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }
        
        .file-selector button:active {
            transform: translateY(0);
        }
        
        .file-info {
            margin-top: 20px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            text-align: left;
            display: none;
        }
        
        .file-info.show {
            display: block;
            animation: fadeInUp 0.5s ease;
        }
        
        .file-info p {
            margin: 8px 0;
            font-size: 0.9em;
        }
        
        .file-path {
            word-break: break-all;
            font-family: 'Monaco', 'Courier New', monospace;
            background: rgba(0, 0, 0, 0.2);
            padding: 8px;
            border-radius: 4px;
        }
        
        .file-analyzer {
            margin-top: 20px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 10px;
        }
        
        .file-analyzer button {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            font-size: 1em;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            margin-bottom: 15px;
        }
        
        .file-analyzer button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }
        
        .file-analyzer button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .analyzer-result {
            display: none;
            margin-top: 15px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            text-align: left;
        }
        
        .analyzer-result.show {
            display: block;
            animation: fadeInUp 0.5s ease;
        }
        
        .analyzer-result h4 {
            margin: 0 0 15px 0;
            color: #ffd700;
            font-size: 1.1em;
            border-bottom: 2px solid rgba(255, 255, 255, 0.2);
            padding-bottom: 8px;
        }
        
        .analyzer-result .stat-item {
            margin: 10px 0;
            padding: 8px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .analyzer-result .stat-label {
            font-weight: 600;
            color: #90EE90;
        }
        
        .analyzer-result .stat-value {
            font-family: 'Monaco', 'Courier New', monospace;
            color: #fff;
        }
        
        .file-preview {
            margin-top: 15px;
            padding: 10px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 5px;
            max-height: 200px;
            overflow-y: auto;
            font-family: 'Monaco', 'Courier New', monospace;
            font-size: 0.85em;
            line-height: 1.6;
        }
        
        .file-preview::-webkit-scrollbar {
            width: 6px;
        }
        
        .file-preview::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
        }
        
        .file-preview::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }
        
        .file-icon {
            font-size: 3em;
            margin: 10px 0;
            text-align: center;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 Hello Electron!</h1>
        <p>欢迎使用 Electron 桌面应用</p>
        <div class="info">
            <h3>系统检测方案对比</h3>
            <p><strong>方式一 (process.platform)</strong>: <span id="os-method1"></span></p>
            <p><strong>方式二 (os.platform)</strong>: <span id="os-method2"></span></p>
            <p><strong>方式三 (os.type)</strong>: <span id="os-method3"></span></p>
            <p><strong>方式四 (navigator.platform)</strong>: <span id="os-method4"></span></p>
            <p><strong>方式五 (navigator.userAgent)</strong>: <span id="os-method5"></span></p>
            
            <h3 style="margin-top: 30px;">版本信息</h3>
            <p>Node.js 版本: <span id="node-version"></span></p>
            <p>Chromium 版本: <span id="chrome-version"></span></p>
            <p>Electron 版本: <span id="electron-version"></span></p>
        </div>
        
        <div class="file-selector">
            <h3>📁 文件选择</h3>
            <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                <button id="select-file-btn">选择文件</button>
                <button id="open-color-picker-btn" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">🎨 打开数码测色计</button>
            </div>
            <div class="file-info" id="file-info">
                <p><strong>已选择文件：</strong></p>
                <p class="file-path" id="file-path"></p>
                <p><strong>文件大小：</strong><span id="file-size"></span></p>
                <p><strong>文件类型：</strong><span id="file-type"></span></p>
                <p><strong>最后修改：</strong><span id="file-modified"></span></p>
            </div>
            
            <div class="file-analyzer" id="file-analyzer" style="display: none;">
                <button id="analyze-file-btn">
                    <span id="analyze-btn-text">🔍 智能分析文件</span>
                    <span id="analyze-loading" class="loading" style="display: none; margin-left: 10px;"></span>
                </button>
                <div class="analyzer-result" id="analyzer-result">
                    <div class="file-icon" id="file-icon"></div>
                    <h4>📊 文件分析结果</h4>
                    <div id="analyzer-stats"></div>
                    <div id="file-preview-container" style="display: none;">
                        <h4 style="margin-top: 15px;">👀 内容预览</h4>
                        <div class="file-preview" id="file-preview"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 引入 Node.js 的 os 和 fs 模块
        const os = require('os');
        const fs = require('fs');
        const path = require('path');
        const { ipcRenderer } = require('electron');
        
        // ========== 方式一：使用 process.platform ==========
        // 这是最常用的方式，返回编译 Node.js 二进制文件的操作系统平台
        // 返回值：'darwin', 'win32', 'linux', 'freebsd', 'openbsd', 'sunos', 'aix'
        function getOSMethod1() {
            const platform = process.platform;
            const arch = process.arch;
            
            const osMap = {
                'darwin': 'macOS',
                'win32': 'Windows',
                'linux': 'Linux',
                'freebsd': 'FreeBSD',
                'openbsd': 'OpenBSD',
                'sunos': 'SunOS',
                'aix': 'AIX'
            };
            
            const osName = osMap[platform] || platform;
            return `${osName} (${arch})`;
        }
        
        // ========== 方式二：使用 os.platform() ==========
        // Node.js os 模块的方法，与 process.platform 返回相同的值
        // 推荐用于需要更多系统信息的场景
        function getOSMethod2() {
            const platform = os.platform();
            const arch = os.arch();
            const release = os.release(); // 系统版本号
            
            const osMap = {
                'darwin': 'macOS',
                'win32': 'Windows',
                'linux': 'Linux',
                'freebsd': 'FreeBSD',
                'openbsd': 'OpenBSD',
                'sunos': 'SunOS',
                'aix': 'AIX'
            };
            
            const osName = osMap[platform] || platform;
            return `${osName} ${release} (${arch})`;
        }
        
        // ========== 方式三：使用 os.type() ==========
        // 返回操作系统的名称，更加详细
        // 返回值：'Linux', 'Darwin', 'Windows_NT' 等
        function getOSMethod3() {
            const type = os.type();
            const arch = os.arch();
            const release = os.release();
            const hostname = os.hostname();
            
            return `${type} ${release} (${arch}) @ ${hostname}`;
        }
        
        // ========== 方式四：使用 navigator.platform ==========
        // 浏览器标准 API，返回浏览器所在平台的字符串
        // 注意：这个值可能被用户代理伪装
        function getOSMethod4() {
            const platform = navigator.platform;
            
            // navigator.platform 可能的返回值：
            // 'MacIntel', 'Win32', 'Win64', 'Linux x86_64', 'Linux armv7l' 等
            let osName = 'Unknown';
            
            if (platform.indexOf('Mac') !== -1) {
                osName = 'macOS (via Navigator)';
            } else if (platform.indexOf('Win') !== -1) {
                osName = 'Windows (via Navigator)';
            } else if (platform.indexOf('Linux') !== -1) {
                osName = 'Linux (via Navigator)';
            } else if (platform.indexOf('iPhone') !== -1 || platform.indexOf('iPad') !== -1) {
                osName = 'iOS (via Navigator)';
            }
            
            return `${osName} - ${platform}`;
        }
        
        // ========== 方式五：使用 navigator.userAgent ==========
        // 解析 User Agent 字符串来判断操作系统
        // 最不推荐的方式，因为 UA 可以被修改
        function getOSMethod5() {
            const ua = navigator.userAgent;
            let osInfo = 'Unknown';
            
            // 检测 macOS
            if (ua.indexOf('Mac OS X') !== -1) {
                const match = ua.match(/Mac OS X (\d+[._]\d+[._]\d+)/);
                if (match) {
                    const version = match[1].replace(/_/g, '.');
                    osInfo = `macOS ${version}`;
                } else {
                    osInfo = 'macOS (version unknown)';
                }
            }
            // 检测 Windows
            else if (ua.indexOf('Windows NT') !== -1) {
                const match = ua.match(/Windows NT (\d+\.\d+)/);
                if (match) {
                    const versionMap = {
                        '10.0': 'Windows 10/11',
                        '6.3': 'Windows 8.1',
                        '6.2': 'Windows 8',
                        '6.1': 'Windows 7',
                        '6.0': 'Windows Vista',
                        '5.1': 'Windows XP'
                    };
                    osInfo = versionMap[match[1]] || `Windows NT ${match[1]}`;
                }
            }
            // 检测 Linux
            else if (ua.indexOf('Linux') !== -1) {
                if (ua.indexOf('Android') !== -1) {
                    osInfo = 'Android (Linux kernel)';
                } else {
                    osInfo = 'Linux';
                }
            }
            // 检测 iOS
            else if (ua.indexOf('iPhone') !== -1 || ua.indexOf('iPad') !== -1) {
                osInfo = 'iOS';
            }
            
            return `${osInfo} (from UA)`;
        }
        
        // ========== 附加信息：系统详细信息 ==========
        function getSystemDetails() {
            return {
                hostname: os.hostname(),
                cpus: os.cpus().length + ' cores',
                totalMemory: (os.totalmem() / 1024 / 1024 / 1024).toFixed(2) + ' GB',
                freeMemory: (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + ' GB',
                uptime: (os.uptime() / 3600).toFixed(2) + ' hours',
                homeDir: os.homedir(),
                tmpDir: os.tmpdir()
            };
        }
        
        // ========== 显示所有检测结果 ==========
        document.getElementById('os-method1').innerText = getOSMethod1();
        document.getElementById('os-method2').innerText = getOSMethod2();
        document.getElementById('os-method3').innerText = getOSMethod3();
        document.getElementById('os-method4').innerText = getOSMethod4();
        document.getElementById('os-method5').innerText = getOSMethod5();
        
        // 显示版本信息
        document.getElementById('node-version').innerText = process.versions.node;
        document.getElementById('chrome-version').innerText = process.versions.chrome;
        document.getElementById('electron-version').innerText = process.versions.electron;
        
        // 在控制台输出详细的系统信息（方便调试）
        console.log('========== 系统检测方案对比 ==========');
        console.log('方式一 (process.platform):', getOSMethod1());
        console.log('方式二 (os.platform):', getOSMethod2());
        console.log('方式三 (os.type):', getOSMethod3());
        console.log('方式四 (navigator.platform):', getOSMethod4());
        console.log('方式五 (navigator.userAgent):', getOSMethod5());
        console.log('\n========== 系统详细信息 ==========');
        console.log(getSystemDetails());
        console.log('\n========== 原始数据 ==========');
        console.log('process.platform:', process.platform);
        console.log('process.arch:', process.arch);
        console.log('os.platform():', os.platform());
        console.log('os.type():', os.type());
        console.log('os.release():', os.release());
        console.log('navigator.platform:', navigator.platform);
        console.log('navigator.userAgent:', navigator.userAgent);
        
        // ========== 文件选择功能 ==========
        const selectFileBtn = document.getElementById('select-file-btn');
        const fileInfo = document.getElementById('file-info');
        const filePathEl = document.getElementById('file-path');
        const fileSizeEl = document.getElementById('file-size');
        const fileTypeEl = document.getElementById('file-type');
        const fileModifiedEl = document.getElementById('file-modified');
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
        }
        
        // 格式化日期
        function formatDate(date) {
            return new Date(date).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }
        
        // 获取文件信息
        function getFileInfo(filePath) {
            try {
                const stats = fs.statSync(filePath);
                const ext = path.extname(filePath).toLowerCase();
                
                return {
                    path: filePath,
                    size: stats.size,
                    type: ext || '未知类型',
                    modified: stats.mtime
                };
            } catch (error) {
                console.error('获取文件信息失败:', error);
                return null;
            }
        }
        
        // 打开颜色拾取器
        const openColorPickerBtn = document.getElementById('open-color-picker-btn');
        openColorPickerBtn.addEventListener('click', async () => {
            try {
                await ipcRenderer.invoke('open-color-picker');
            } catch (error) {
                console.error('打开颜色拾取器失败:', error);
                alert('打开颜色拾取器失败: ' + error.message);
            }
        });
        
        // 处理文件选择
        let currentFilePath = null;
        
        selectFileBtn.addEventListener('click', async () => {
            try {
                const result = await ipcRenderer.invoke('select-file');
                
                if (result.success && result.filePath) {
                    currentFilePath = result.filePath;
                    const fileInfoData = getFileInfo(result.filePath);
                    
                    if (fileInfoData) {
                        filePathEl.textContent = fileInfoData.path;
                        fileSizeEl.textContent = formatFileSize(fileInfoData.size);
                        fileTypeEl.textContent = fileInfoData.type;
                        fileModifiedEl.textContent = formatDate(fileInfoData.modified);
                        fileInfo.classList.add('show');
                        
                        // 显示分析器
                        document.getElementById('file-analyzer').style.display = 'block';
                        document.getElementById('analyzer-result').classList.remove('show');
                    } else {
                        alert('无法读取文件信息');
                    }
                } else {
                    console.log('用户取消了文件选择');
                }
            } catch (error) {
                console.error('选择文件时出错:', error);
                alert('选择文件时出错: ' + error.message);
            }
        });
        
        // ========== 文件分析功能 ==========
        const analyzeBtn = document.getElementById('analyze-file-btn');
        const analyzeBtnText = document.getElementById('analyze-btn-text');
        const analyzeLoading = document.getElementById('analyze-loading');
        const analyzerResult = document.getElementById('analyzer-result');
        const analyzerStats = document.getElementById('analyzer-stats');
        const fileIcon = document.getElementById('file-icon');
        const filePreview = document.getElementById('file-preview');
        const filePreviewContainer = document.getElementById('file-preview-container');
        
        // 获取文件类型图标
        function getFileIcon(ext) {
            const iconMap = {
                '.txt': '📄', '.md': '📝', '.json': '📋', '.js': '📜', '.html': '🌐',
                '.css': '🎨', '.jpg': '🖼️', '.jpeg': '🖼️', '.png': '🖼️', '.gif': '🖼️',
                '.mp4': '🎬', '.avi': '🎬', '.mov': '🎬', '.pdf': '📕', '.doc': '📘',
                '.docx': '📘', '.xls': '📊', '.xlsx': '📊', '.zip': '📦', '.rar': '📦',
                '.exe': '⚙️', '.dmg': '💿', '.app': '📱', '.py': '🐍', '.java': '☕',
                '.cpp': '⚡', '.c': '⚡', '.go': '🐹', '.rs': '🦀', '.php': '🐘'
            };
            return iconMap[ext.toLowerCase()] || '📁';
        }
        
        // 检测文件编码（简单检测）
        function detectEncoding(buffer) {
            // 检查 BOM
            if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
                return 'UTF-8 (BOM)';
            }
            if (buffer[0] === 0xFF && buffer[1] === 0xFE) {
                return 'UTF-16 LE';
            }
            if (buffer[0] === 0xFE && buffer[1] === 0xFF) {
                return 'UTF-16 BE';
            }
            
            // 简单检测：检查是否包含非 ASCII 字符
            let hasNonAscii = false;
            for (let i = 0; i < Math.min(buffer.length, 1000); i++) {
                if (buffer[i] > 127) {
                    hasNonAscii = true;
                    break;
                }
            }
            
            return hasNonAscii ? 'UTF-8 (可能)' : 'ASCII';
        }
        
        // 分析文本文件
        function analyzeTextFile(content, encoding) {
            const lines = content.split('\n');
            const words = content.split(/\s+/).filter(w => w.length > 0);
            const chars = content.length;
            const charsNoSpaces = content.replace(/\s/g, '').length;
            
            return {
                type: 'text',
                encoding: encoding,
                lines: lines.length,
                words: words.length,
                characters: chars,
                charactersNoSpaces: charsNoSpaces,
                paragraphs: content.split(/\n\s*\n/).filter(p => p.trim().length > 0).length
            };
        }
        
        // 分析图片文件（通过文件头）
        function analyzeImageFile(buffer) {
            // PNG: 89 50 4E 47
            if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) {
                const width = (buffer[16] << 24) | (buffer[17] << 16) | (buffer[18] << 8) | buffer[19];
                const height = (buffer[20] << 24) | (buffer[21] << 16) | (buffer[22] << 8) | buffer[23];
                return {
                    type: 'image',
                    format: 'PNG',
                    width: width,
                    height: height,
                    colorDepth: buffer[24] * 8 || '未知'
                };
            }
            // JPEG: FF D8 FF
            if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {
                // JPEG 尺寸解析较复杂，这里简化处理
                return {
                    type: 'image',
                    format: 'JPEG',
                    width: '需完整解析',
                    height: '需完整解析'
                };
            }
            // GIF: 47 49 46 38
            if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38) {
                const width = buffer[7] << 8 | buffer[6];
                const height = buffer[9] << 8 | buffer[8];
                return {
                    type: 'image',
                    format: 'GIF',
                    width: width,
                    height: height
                };
            }
            return null;
        }
        
        // 分析文件
        async function analyzeFile(filePath) {
            try {
                const stats = fs.statSync(filePath);
                const ext = path.extname(filePath).toLowerCase();
                const buffer = fs.readFileSync(filePath);
                const encoding = detectEncoding(buffer);
                
                // 显示文件图标
                fileIcon.textContent = getFileIcon(ext);
                
                const statsHtml = [];
                
                // 基础信息
                statsHtml.push(`
                    <div class="stat-item">
                        <span class="stat-label">文件扩展名</span>
                        <span class="stat-value">${ext || '无'}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">创建时间</span>
                        <span class="stat-value">${formatDate(stats.birthtime)}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">访问时间</span>
                        <span class="stat-value">${formatDate(stats.atime)}</span>
                    </div>
                `);
                
                // 文本文件分析
                const textExtensions = ['.txt', '.md', '.json', '.js', '.html', '.css', '.py', '.java', '.cpp', '.c', '.go', '.rs', '.php', '.xml', '.yaml', '.yml'];
                if (textExtensions.includes(ext)) {
                    try {
                        const content = buffer.toString('utf-8');
                        const analysis = analyzeTextFile(content, encoding);
                        
                        statsHtml.push(`
                            <div class="stat-item" style="background: rgba(255, 215, 0, 0.2); margin-top: 15px;">
                                <span class="stat-label">📝 文本分析</span>
                                <span class="stat-value"></span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">编码格式</span>
                                <span class="stat-value">${analysis.encoding}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">总行数</span>
                                <span class="stat-value">${analysis.lines.toLocaleString()}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">单词数</span>
                                <span class="stat-value">${analysis.words.toLocaleString()}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">字符数（含空格）</span>
                                <span class="stat-value">${analysis.characters.toLocaleString()}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">字符数（不含空格）</span>
                                <span class="stat-value">${analysis.charactersNoSpaces.toLocaleString()}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">段落数</span>
                                <span class="stat-value">${analysis.paragraphs}</span>
                            </div>
                        `);
                        
                        // 显示预览（前20行）
                        const previewLines = content.split('\n').slice(0, 20);
                        filePreview.textContent = previewLines.join('\n');
                        if (previewLines.length < analysis.lines) {
                            filePreview.textContent += '\n\n... (还有 ' + (analysis.lines - previewLines.length) + ' 行)';
                        }
                        filePreviewContainer.style.display = 'block';
                    } catch (e) {
                        statsHtml.push(`
                            <div class="stat-item">
                                <span class="stat-label">⚠️ 无法读取文本内容</span>
                                <span class="stat-value">${e.message}</span>
                            </div>
                        `);
                    }
                }
                
                // 图片文件分析
                if (['.jpg', '.jpeg', '.png', '.gif', '.bmp'].includes(ext)) {
                    const imageAnalysis = analyzeImageFile(buffer);
                    if (imageAnalysis) {
                        statsHtml.push(`
                            <div class="stat-item" style="background: rgba(255, 215, 0, 0.2); margin-top: 15px;">
                                <span class="stat-label">🖼️ 图片分析</span>
                                <span class="stat-value"></span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">图片格式</span>
                                <span class="stat-value">${imageAnalysis.format}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">宽度</span>
                                <span class="stat-value">${imageAnalysis.width} px</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">高度</span>
                                <span class="stat-value">${imageAnalysis.height} px</span>
                            </div>
                            ${imageAnalysis.colorDepth ? `
                            <div class="stat-item">
                                <span class="stat-label">颜色深度</span>
                                <span class="stat-value">${imageAnalysis.colorDepth} bit</span>
                            </div>
                            ` : ''}
                        `);
                        
                        // 显示图片预览
                        const img = document.createElement('img');
                        img.src = `file://${filePath}`;
                        img.style.maxWidth = '100%';
                        img.style.maxHeight = '200px';
                        img.style.borderRadius = '8px';
                        img.style.marginTop = '10px';
                        filePreview.innerHTML = '';
                        filePreview.appendChild(img);
                        filePreviewContainer.style.display = 'block';
                    }
                }
                
                analyzerStats.innerHTML = statsHtml.join('');
                analyzerResult.classList.add('show');
                
            } catch (error) {
                console.error('分析文件失败:', error);
                analyzerStats.innerHTML = `
                    <div class="stat-item" style="background: rgba(255, 0, 0, 0.2);">
                        <span class="stat-label">❌ 分析失败</span>
                        <span class="stat-value">${error.message}</span>
                    </div>
                `;
                analyzerResult.classList.add('show');
            }
        }
        
        // 绑定分析按钮
        analyzeBtn.addEventListener('click', async () => {
            if (!currentFilePath) {
                alert('请先选择一个文件');
                return;
            }
            
            analyzeBtn.disabled = true;
            analyzeBtnText.textContent = '分析中';
            analyzeLoading.style.display = 'inline-block';
            filePreviewContainer.style.display = 'none';
            analyzerResult.classList.remove('show');
            
            try {
                await analyzeFile(currentFilePath);
            } catch (error) {
                console.error('分析出错:', error);
                alert('分析文件时出错: ' + error.message);
            } finally {
                analyzeBtn.disabled = false;
                analyzeBtnText.textContent = '🔍 智能分析文件';
                analyzeLoading.style.display = 'none';
            }
        });
    </script>
</body>
</html>

